package com.ysd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.ysd.common.constant.ProductConstant;
import com.ysd.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.ysd.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.ysd.gulimall.product.entity.AttrGroupEntity;
import com.ysd.gulimall.product.entity.CategoryEntity;
import com.ysd.gulimall.product.service.AttrAttrgroupRelationService;
import com.ysd.gulimall.product.service.AttrGroupService;
import com.ysd.gulimall.product.service.CategoryService;
import com.ysd.gulimall.product.vo.AttrGroupRelationVo;
import com.ysd.gulimall.product.vo.AttrRespVo;
import com.ysd.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.utils.PageUtils;
import com.ysd.common.utils.Query;

import com.ysd.gulimall.product.dao.AttrDao;
import com.ysd.gulimall.product.entity.AttrEntity;
import com.ysd.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //1、先存入Attr表基本数据
        AttrEntity attrEntity = new AttrEntity();
        //Spring copy工具类   前提vo属性名====po属性名
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //2、再存关联信息
        //规格参数加的判断              判断 分组不为空再保存关联关系
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //拼接查询销售和基本判断           枚举
        wrapper.eq("attr_type",
                "base".equalsIgnoreCase(attrType) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //根据不同情况封装查询条件
        //0 查询所有 ！= 0查询子分类
        if (catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }
        //检索条件判断
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            //attr_id attr_name
            wrapper.and((wr) ->{
                wr.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        //查询结果集
        List<AttrEntity> records = page.getRecords();
        //流式处理
        List<AttrRespVo> respVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //1、拷贝基本信息
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //2、设置分类和分组的名字
            //规格参数时加的参数判断
            if("base".equalsIgnoreCase(attrType)) {
                //先查询关联表的数据
                AttrAttrgroupRelationEntity relationEntity
                        = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                //获取组id
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    //根据组id获取组name
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if(attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        //设置最新结果集
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //创建返回对象
        AttrRespVo attrRespVo = new AttrRespVo();

        //1、先根据attrId 查询属性数据库详细信息
        AttrEntity attrEntity = this.getById(attrId);
        //Copy     第一个参数是出 源对象 attrEntity  第二个是入 目标对象attrRespVo
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        /**
         * "attrGroupId": 1, //分组id
         * "catelogId": 225, //分类id   内置有
         * "catelogPath": [2, 34, 225] //分类完整路径
         */
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //基础参数  需要设置分组
            /**
             * 分组id
             * 1、通过Attr属性和AttrGroup分组的关联表查询
             */
            AttrAttrgroupRelationEntity relationEntity  = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            //2、分组关联对象 查询分组id
            //先判断后设置
            if(relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                //同时查询封装分组的名称
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                //再判断
                if(attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2、设置分类信息  目前是
        //取出分类id
        Long catelogId = attrEntity.getCatelogId();
        //根据id查询分类完成路径
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        //设置完成路径引用
        attrRespVo.setCatelogPath(catelogPath);
        //获取第三级分类的名字
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if(categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        //1、先修改数据库中Attr表的基本数据
        //创建Attr实体类
        AttrEntity attrEntity = new AttrEntity();
        //copy
        BeanUtils.copyProperties(attr,attrEntity);
        //调用修改方法
        this.updateById(attrEntity);

        /**
         * 只有基础属性才需要设置分组  关联分组
         */
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //设置分组id和属性id
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrgroupRelationEntity.setAttrId(attr.getAttrId());

            //先判断当前attrid是否关联了分组id
            int count = relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            //大于0 修改  反之新增关联
            if(count > 0) {
                //2、修改分组关联   sql  根据attrid修改attrgroupid
                relationService.update(attrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            } else {
                //3、新增分组关联
                relationService.save(attrgroupRelationEntity);
            }
        }
    }

    /**
     * 根据分组id查询所有关联的基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntityList = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        //收集所有的属性id
        List<Long> attrIds = relationEntityList.stream().map((relationEntity) -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());
        //按照属性的id集合查询出属性信息
//        List<AttrEntity> attrs = new ArrayList<>();
//        for (Long attrId: attrIds) {
//            AttrEntity attrEntity = this.getById(attrId);
//            attrs.add(attrEntity);
//        }
        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        List<AttrEntity> attrEntities = (List<AttrEntity>) this.listByIds(attrIds);
        return attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //技术突破  只发一次请求批量删除
        //将控制层收集的数据copy到实体类AttrAttrgroupRelationEntity中
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //自写方法
        relationDao.removeBatchRelation(entities);
    }

    /**
     * 获取当前属性分组没有关联的其他属性
     * 注意：
     *  1、当前分组只能关联自己所属分类的属性
     *  1.2、获取当前分组的分类信息
     *  2.1、获取当前分类下的所有分组
     *  2、当前分组只能关联没有被引用的属性
     *  2.2.1 分组id集合
     *  3、分组只管关联基本属性不关联销售属性
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //1、当前分组只能关联自己所属分类的属性
        //1.1、根据分组id先查分组信息
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        //1.2、获取当前分组的分类信息
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联没有被引用的属性
        //2.1、获取当前分类下的所有分组
        List<AttrGroupEntity> groupList = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2.2、获取这个分组关联的属性
        //2.2.1 分组id集合
        List<Long> groupIdList = groupList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //缺一个分空判断
        //2.2.2 获取其他分组关联属性
        List<AttrAttrgroupRelationEntity> relationList = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdList));
        //2.3、排除法
        //拿到所有其他分组关联的属性的id
        List<Long> attrIdList = relationList.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //排除并获取当前分类下的不是这些属性id的属性
        //多条件+分页+排除
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIdList != null && attrIdList.size() > 0) {
            wrapper.notIn("attr_id", attrIdList);
        }
        //多条件
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            //非空拼接
            wrapper.and((w) -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        PageUtils pageUtils = new PageUtils(this.page(new Query<AttrEntity>().getPage(params), wrapper));
        return pageUtils;
    }


}